package com.innovation.ic.cyz.web.schedule;

import com.innovation.ic.cyz.base.pojo.enums.RedisKeyPrefixEnum;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.web.thread.HandleProductsDataThread;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @desc   导入标准库产品表数据定时任务
 * @author linuo
 * @time   2022年10月31日09:27:34
 */
@Component
public class ImportProductDataTask extends AbstractSchedule {
    private static final Logger log = LoggerFactory.getLogger(ImportProductDataTask.class);

    /**
     * 获取标准库Products表数据导入到cyz的数据库中
     */
    @XxlJob("importProductDataTaskJobHandler")
    private ReturnT<String> importProductDataTaskJob() {
        log.info("定时任务开启: 先删除本地product表的数据,获取标准库products表数据导入到cyz的数据库中");

        // 清空product表数据
        productService.truncateProduct();

        //清空redis数据
        String key = RedisKeyPrefixEnum.TABLE.getCode() + ":" + RedisKeyPrefixEnum.TABLE_PRODUCT.getCode();
        super.deleteRedisKey(key);
        // 查询标准库Products状态是正常的数据数量
        ServiceResult<Long> result = productsService.getNormalStatusDataCount();
        Long count = result.getResult();
        if(count != null && count > 0){
            log.info("Products表共有[{}]条数据需要处理", count);

            // 最大线程数
            int maxThreadCount = 10;

            // 每个线程处理的数据数量
            int threadHandleDataCount = (int)Math.ceil(count * 1.0 / maxThreadCount);

            for (int i = 0; i < maxThreadCount; i++) {
                long start = threadHandleDataCount * i + 1;
                long end = threadHandleDataCount * (i + 1);
                if(end > count){
                    end = count;
                }
                // 创建多线程处理标准库Products数据
                HandleProductsDataThread handleProductsDataThread = new HandleProductsDataThread(productsService, productService, start, end);
                handleProductsDataThread.setDaemon(Boolean.TRUE);
                threadPoolManager.execute(handleProductsDataThread);
            }
        }

        return ReturnT.SUCCESS;
    }
}